import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

import { logout, login, getUser, getUserByCRP } from '@/api/user'
import { getRole } from '@/api/role'
export default new Vuex.Store({
  state: {
    roles: [],
    username: ''
  },
  getters: {
    // userRole: state => state.user.role,
    username: state => state.username,
    roles: state => state.roles
  },
  mutations: {
    SET_USER(state, username) {

      state.username = username;
    },
    SET_ROLES(state, roles) {
      console.log('set roles', roles)
      state.roles = roles;
    }
  },
  actions: {
    setUserInfo({ commit }, user) {
      commit('SET_USER', user);
    },
    LogOut({ commit }) {
      console.log('logout')
      return new Promise((resolve, reject) => {
        logout().then(res => {
          localStorage.removeItem('username')
          localStorage.removeItem('roleName')
          localStorage.removeItem('userId')
          localStorage.removeItem('authToken');
          localStorage.removeItem("CRP")
          resolve()
        }).catch(err => {
          reject(err)
        })
      })

    },
    doLogin({ commit }, formData) {
      return new Promise((resolve, reject) => {
        login(formData).then(res => {
          if (res.code == 200) {
            console.log('登录成功！')
            localStorage.setItem('authToken', res.data.token);
          }
          resolve()
        }).catch(err => {
          reject(err)
        })
      })

    },
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getUser().then(res => {
          console.log('store getuser', res);
          commit('SET_USER', res.data.username)

          // 后端的角色设计有问题，这里暂时设置为所有人都是teacher角色
          commit('SET_ROLES', ['teacher'])

          localStorage.setItem('username', res.data.username);
          localStorage.setItem('CRP', res.data.username);
          localStorage.setItem('userId', res.data.id);
         
          
          getUserByCRP(res.data.username).then(rsp=>{
            console.log("getUserByCRP result", rsp);
            const roleId = rsp.data.roleId;
            getRole(roleId).then(role => {
              console.log("roleName get result", role)
              if (role.code == 200) {
                localStorage.setItem("roleName", role.data[0].name)
              }
            })
          })
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    }




  }
})
